Reverse a Sentence Using Recursion with C++

04-11-17 Course- CPP

This program takes a sentence from user and reverses that sentence using recursion.

Source code to reverse a sentence using recursion.


/* Example to reverse a sentence entered by user. */

#include <iostream>
#include <string>
using namespace std;
void reverse(const string& a);
int main()
{
    string a;
    cout << " Please enter a string " << endl;
    getline(cin, a);
    reverse(a);
    return 0;    
}
void reverse(const string& a)
{
    size_t n = a.size();
    if(n == 1)
       cout << a << endl;
    else
    {
       cout << a[n-1];
       string b = a.substr(0, n-1);
       reverse(b);
    }    
}

Output


Enter a sentence: margorp emosewa
awesome program